#include<stdio.h>
#include "hash_table.h"

hashtable *create_hashtable(size_t size)
{
	int i;
	hashtable *pthis = (hashtable*)malloc(sizeof(hashtable));
	pthis->base = (void*)malloc(sizeof(node*)*size);
	pthis->size = size;
	for(i=0;i < pthis->size;i++)
	{
		(*pthis->base)[i] = NULL;
	}
	return pthis;
}

element * create_element(void *data,int key,size_t size)
{
	void *p = malloc(sizeof(char)*size);
	element *e = (element*)malloc(sizeof(element));
	memcpy(p,data,size);
	e->data = p;
	e->key = key;
	e->size = size;
	return e;
}

int mapping(hashtable *pthis,int key)
{
	return key % pthis->size;
	//the function is h in CLRS, map key to hashtable
}

void chained_hash_insert(hashtable *pthis,element *e)
{
	int cur = mapping(pthis,e->key);
	list_insert_front(&((*pthis->base)[cur]),e);
}

element* chained_hash_search(hashtable *pthis,int key)
{
	int cur;
	cur = mapping(pthis,key);
	return list_search((*pthis->base)[cur],key);
}

void print_hash_data(hashtable *pthis)
{
	int i = 0;

	while(i < pthis->size)
	{
		printf("A[%d] -> ",i);
		if((*pthis->base)[i]!=NULL)
		{
			print_list((*pthis->base)[i]);
			printf("\n");
		}
		else
		{
			printf("NULL\n");
		}
		i++;
	}
}

void destroy_hashtable(hashtable *pthis)
{
	int i = 0;

	while(i < pthis->size)
	{
		if((*pthis->base)[i] != NULL)
		{
			list_destroy((*(pthis->base))[i]);
		}
		i++;
	}
	free(pthis->base);
	free(pthis);//i'm forget it again
}




